import React, { useEffect, useRef, useState } from 'react';
import './index.less';
import {
  Divider,
  Menu,
  Switch,
  Collapse,
  Checkbox,
  Tree,
  Button,
  message,
  Spin,
  Modal,
} from 'antd';
import { request } from 'umi';
import EditCom from './edit';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
const { Panel } = Collapse;
export default (props: any) => {
  const [items, setItems] = useState([]);
  const [selectKey, setselectKey] = useState('');
  const [allMenus, setAllMenus] = useState([]);
  const [checkedKeys, setcheckedKeys] = useState([]);
  const [halfCheckedKeys, sethalfCheckedKeys] = useState([]);
  const [loading, setloading] = useState(false);
  const editRef = useRef();
  const getRoles = () => {
    request('/sys/role/roleList', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {},
    }).then((res) => {
      console.log(res);
      const rolelist = res?.data || [];
      rolelist.map((e: any, i: Number) => {
        rolelist[i]['label'] = e['roleName'];
        rolelist[i]['key'] = e['roleId'];
      });
      if (selectKey == '') {
        setselectKey(rolelist[0]['key']);
      }

      setItems(rolelist);
    });
  };
  const getAllMenus = () => {
    request('/sys/menu/getTreeList', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {},
    }).then((res) => {
      console.log(res);
      setAllMenus(res?.data || []);
    });
  };
  const distributionShiro = () => {
    request('/sys/role/distributionShiro', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      data: {
        menuIdList: checkedKeys.concat(halfCheckedKeys),
        roleId: selectKey,
      },
    }).then((res) => {
      console.log(res);
      message.success(res?.mate?.msg || '保存成功');
      // getAllMenus();
      // getAllHasMenus();
      getgetCheckedTreeList();
    });
  };
  const getgetCheckedTreeList = () => {
    if (selectKey) {
      setloading(true);
      request('/sys/menu/getCheckedTreeList', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        data: {
          roleId: selectKey,
        },
      }).then((res) => {
        setloading(false);
        let treedata = res?.data || [];
        let checkedKeysn = [];
        let halfCheckedKeysn = [];
        const handlecheckeddata = (data: any) => {
          data.map((e: any, i: number) => {
            if (e.checkedStatus == 1) {
              checkedKeysn.push(e.id);
            } else if (e.checkedStatus == 2) {
              halfCheckedKeysn.push(e.id);
            }
            let children = e.children || [];
            if (children.length > 0) {
              handlecheckeddata(children);
            }
          })

        }
        handlecheckeddata(treedata);
        console.log(JSON.stringify(checkedKeysn));
        console.log(JSON.stringify(halfCheckedKeysn));
        setAllMenus(treedata);
        setcheckedKeys(checkedKeysn);
        sethalfCheckedKeys(halfCheckedKeysn);
      })
    }

  }

  useEffect(() => {
    // getAllMenus();
    // getAllHasMenus();
    getgetCheckedTreeList();
  }, [selectKey]);
  useEffect(() => {
    getRoles();
  }, []);
  const deleteFn = (id) => {
    Modal.confirm({
      title: '确认删除？',
      content: '',
      onOk() {
        console.log('OK');

        request('/sys/role/deleteRole', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          data: {
            roleId: id,
          },
        }).then(() => {
          if (id == selectKey) {
            setselectKey('');
          }
          getRoles();
          setloading(false);
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  return (
    <div className="RolesContainer">
      <div className="rolesMenus">
        <div style={{ marginBottom: '10px' }}>
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              editRef.current?.init();
            }}
            type="primary"
          >
            新建
          </Button>
          ,
        </div>
        <Menu
          onClick={(e) => {
            setselectKey(e.key);
          }}
          selectedKeys={[selectKey]}
        >
          {items.map((item: any, i: number) => {
            return (
              <Menu.Item key={item.key}>
                <div>
                  <EditOutlined
                    onClick={(e) => {
                      editRef.current?.init(item.key);
                      e.stopPropagation();
                    }}
                  />
                  <DeleteOutlined onClick={() => deleteFn(item.key)} />
                  <span style={{ marginLeft: '10px' }}>{item.label}</span>
                </div>
              </Menu.Item>
            );
          })}
        </Menu>
      </div>
      <div className="rolesContent">
        <div className="roleContentC">
          <Spin spinning={loading}>
            <Tree
              treeData={allMenus}
              onCheck={(checkeds: any, e) => {
                console.log(checkeds);
                console.log(e);
                setcheckedKeys(checkeds);
                sethalfCheckedKeys(e.halfCheckedKeys);
              }}
              checkedKeys={{
                checked: checkedKeys,
                halfChecked: halfCheckedKeys
              }}
              multiple
              blockNode={true}
              checkable
              fieldNames={{
                title: 'name',
                key: 'id',
              }}
            ></Tree>
          </Spin>
        </div>
        <div className="roleContentB">
          <Button
            onClick={() => {
              distributionShiro();
            }}
            type="primary"
          >
            保存
          </Button>
        </div>
      </div>
      <EditCom
        ref={editRef}
        callback={() => {
          getRoles();
        }}
      />
    </div>
  );
};
